<template>
  <div class="example-block">
    <el-cascader placeholder="根目录" :options="folderOptions" filterable size="small" :debounce="100"
      v-model="selectedFolder" @change="valueChange" :props="propsOption" clearable>
      <template #default="{ node, data }">
        <span>{{ data.label }}</span>
        <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
      </template>
    </el-cascader>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, getCurrentInstance } from "vue";
import { get } from "@/tools/api/api";
import { folderType } from "./folder";
import { debounce } from "@/hooks/tools";
import { usePhotoStore } from "@/store/photo";
// 引入仓库
const photoStore = usePhotoStore()
// 创建实例
const instance = getCurrentInstance();

/**
 * 选择框配置套餐
 */
// 接收父组件的参数及类型
defineProps<Props>()
type Props = {
  propsOption?: {
    checkStrictly?: boolean,  //是否可以选择任一级
    multiple?: boolean    //是否支持多选
  }
}


onMounted(() => {
  // 同步仓库数据
  selectedFolder.value = photoStore.currentFolder;
  // 获取指定数据，并判断是否显示所有层级
  judgeShowAllLevel();
})

// 判断是否显示所有层级
const judgeShowAllLevel = () => {
  // 异步延时，防止仓库修改前挂载
  setTimeout(() => {
    if (!photoStore.showAllLevel) {
      getFavoriteWithoutSmall()
    } else getFavorite()
  }, 10);
}

instance?.proxy?.$Bus.on("reloadFolder", () => {
  judgeShowAllLevel()
})

// 选中的收藏夹数据
const selectedFolder = ref<string[]>([])

// 选中的收藏夹发生变化时
const valueChange = debounce((value: any) => {
  // 更新仓库数据
  photoStore.$patch((state) => {
    state.currentFolder = value
  })
  //将选中的数据派发给其它组件
  selectedFolder.value = value
  instance?.proxy?.$Bus.emit("selectedFolderData", selectedFolder.value)

}, 200)

// 获取所有收藏夹
const folderOptions = ref(<folderType[]>[])
const getFavorite = () => {
  get("getFavorite").then((res: any) => {

    if (res.code === 100) {
      folderOptions.value = res.data
      photoStore.$patch((state) => {
        state.allFolder = res.data
      })
    }
  })
}

// 获取大中层级的收藏夹
const getFavoriteWithoutSmall = () => {
  get("getFavorite", {
    method: -1
  }).then((res: any) => {

    if (res.code === 100) {
      folderOptions.value = res.data
      photoStore.$patch((state) => {
        state.allFolderWithoutSmall = res.data
      })
    }
  })
}

</script>

<style lang="scss" scoped>
$header-height: 0.3rem;
$logo-width: 0.6rem;
$a-font-size: 0.08rem;
$theme-color: rgb(96, 197, 186); //#5fc5ba

// 整个选择框组件
.example-block {
  margin: 0.1rem;

  // 选择的input
  ::v-deep(.el-input__inner) {
    width: auto;
    max-width: 3rem;
  }
}
</style>
